package com.zzh.custom.recycler;

import android.util.SparseArray;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public class ChaosAdapter<B extends ChaosBean, I extends ChaosItem<B, V>, V extends ChaosViewHolder> extends RecyclerView.Adapter<V> {

    private List<B> mList;
    private SparseArray<I> mChaosItems = new SparseArray<>();
    private ChaosDefaultItem chaosDefaultItem = new ChaosDefaultItem();

    private ChaosAdapter(List<B> list, I... items) {
        mList = list;
        mChaosItems.clear();
        for (I item : items) {
            if (item instanceof BaseChaosItem) {
                ((BaseChaosItem<?, ?>) item).setAdapter(this);
            }
            mChaosItems.append(item.getChaosItemType(), item);
        }
    }


//    public static <B extends ChaosBean, V extends ChaosViewHolder, I extends BaseChaosItem<B, V>> ChaosAdapter<B, I, V>
//    createAdapter(List<B> list, I... items) {
//        return new ChaosAdapter<>(list, items);
//    }

//    public static ChaosAdapter createAdapter(List<ChaosBean> list, BaseChaosItem... items) {
//        return new ChaosAdapter<>(list, items);
//    }


    public static ChaosAdapter createAdapter (List<? extends ChaosBean> list,
                                              BaseChaosItem<? extends ChaosBean,? extends ChaosViewHolder>... items) {
        return new ChaosAdapter(list, items);
    }


    @NonNull
    @Override
    public V onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        I i = mChaosItems.get(viewType);
        if (i == null) {
            return (V) chaosDefaultItem.createViewHolder(parent);
        }
        return i.createViewHolder(parent);
    }


    @Override
    public void onBindViewHolder(@NonNull V holder, int position) {
        B bean = mList.get(position);
        I i = mChaosItems.get(bean.getChaosItemType());
        if (i != null) {
            i.onBindViewHolder(holder, position, bean);
        }
    }


    @Override
    public int getItemCount() {
        return mList == null ? 0 : mList.size();
    }

    @Override
    public int getItemViewType(int position) {
        return mList.get(position).getChaosItemType();
    }

    public List<B> getList() {
        return mList;
    }

    public void updateAdapter(List<B> list) {
        mList = list;
        notifyDataSetChanged();
    }

    public void submitAdapter(List<B> list) {
        if (list == null) return;
        if (mList == null) {
            mList = new ArrayList<>();
        }
        int startIndex = mList.size();
        mList.addAll(list);
        notifyItemRangeChanged(startIndex, list.size());
    }

}
